package com.itheima.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.entity.PageResult;
import com.itheima.common.pojo.Member;
import com.itheima.common.pojo.Order;
import com.itheima.common.pojo.OrderSetting;
import com.itheima.common.pojo.dto.OrderSettingPageQueryDTO;
import com.itheima.common.pojo.vo.OrderVO;
import com.itheima.mapper.OrderSettingMapper;
import com.itheima.service.OrderSettingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingMapper orderSettingMapper;


    /**
     * 分页查询预约设置
     * @param orderSettingDTO
     * @return
     */
    public PageResult pageQuery(OrderSettingPageQueryDTO orderSettingDTO) {
        PageHelper.startPage(orderSettingDTO.getCurrentPage(), orderSettingDTO.getPageSize());
        Page<OrderVO> page = orderSettingMapper.pageQuery(orderSettingDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 修改预约设置
     * @param order
     */
    public void update(Order order) {
        orderSettingMapper.update(order);
    }

    /**
     * 根据月份查询预约设置数据
     * @param month
     * @return
     */
    public List<Map<String, Object>> getOrderSettingByMonth(String month) {
        //beginDate 将传入的月份与 -1 拼接，表示该月的第一天
        String beginDate = month + "-1";
        String endDate = month + "-31";
        List<OrderSetting> list = orderSettingMapper.getOrderSettingByMonth(beginDate, endDate);
        List<Map<String,Object>> data = new ArrayList<>();
        for (OrderSetting orderSetting : list) {
            //将每个OrderSetting对象的日期、数量和预约数封装为Map，并添加到此集合中
            Map<String, Object> map = new HashMap<>();
            map.put("date", orderSetting.getOrderDate().getDate());
            map.put("number", orderSetting.getNumber());
            map.put("reservations", orderSetting.getReservations());
            data.add(map);
        }
        return data;
    }

    /**
     * 导出预约设置数据
     * @param response
     */
    public void dowload(HttpServletResponse response) {
        try {
            //1.创建工作薄
            XSSFWorkbook workbook = new XSSFWorkbook();
            //2.创建工作表
            XSSFSheet sheet = workbook.createSheet("预约设置信息");

            //3.创建表头
            XSSFRow header = sheet.createRow(0);
            header.createCell(0).setCellValue("日期");
            header.createCell(1).setCellValue("可预约数量");

            //4.查询数据
            List<OrderSetting> list = orderSettingMapper.findAll();

            //5.遍历数据，创建数据行
            int rowNum = 1;
            for (OrderSetting orderSetting : list) {
                XSSFRow dataRow = sheet.createRow(rowNum++);
                dataRow.createCell(0).setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(orderSetting.getOrderDate()));
                dataRow.createCell(1).setCellValue(orderSetting.getNumber());
            }

            //6.设置响应头
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=orderSetting.xlsx");

            //7.写出数据
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (Exception e) {
            log.error("导出预约设置数据失败", e);
            throw new RuntimeException("导出预约设置数据失败");
        }
    }

    /**
     * 导入预约设置数据
     * @param file
     */
    @Transactional
    public void importExcel(MultipartFile file) {
        try {
            //1.创建工作薄
            XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
            //2.获取第一个工作表
            XSSFSheet sheet = workbook.getSheetAt(0);

            //3.遍历数据行
            for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
                //根据行号从工作表中获取指定行的数据
                XSSFRow row = sheet.getRow(rowNum);
                if (row != null) {
                    //4.获取单元格数据
                    String dateStr = row.getCell(0).getStringCellValue();
                    double number = row.getCell(1).getNumericCellValue();
                    //5.封装成OrderSetting对象
                    OrderSetting orderSetting = new OrderSetting();
                    //将字符串格式的日期解析为Date类型并设置到OrderSetting对象中
                    orderSetting.setOrderDate(new SimpleDateFormat("yyyy-MM-dd").parse(dateStr));
                    orderSetting.setNumber((int) number);
                    //6.判断数据是否存在
                    Long count = orderSettingMapper.findCountByOrderDate(orderSetting.getOrderDate());
                    if (count > 0) {
                        // 如果存在，则更新
                        orderSettingMapper.editNumberByOrderDate(orderSetting);
                    } else {
                        // 如果不存在，则添加
                        orderSetting.setReservations(0);
                        orderSettingMapper.add(orderSetting);
                    }
                }
            }
            workbook.close();
        } catch (Exception e) {
            log.error("导入预约设置数据失败", e);
            throw new RuntimeException("导入预约设置数据失败");
        }
    }

}
